package _case

import (
	"errors"
	"fmt"
	"log"
	"time"
)

type cusError struct {
	Code int
	Msg  string
	Time time.Time
}

// 实现了error接口
//
//	type error interface {
//		Error() string
//	}
func (e cusError) Error() string {
	return fmt.Sprintf("Code: %d,Msg: %s,Time: %s", e.Code, e.Msg, e.Time.Format("2006-01-02 15:04:05Z"))
}

func getCusError(code int, msg string) error {
	return cusError{code, msg, time.Now()}
}

func ErrorCase() {
	err := errors.New("程序发生错误")
	fmt.Println(err)

	var a, b = -1, -2
	num, err := sum(a, b)
	fmt.Println(num, err)
	if err != nil {
		log.Println(err)
		cusErr, ok := err.(cusError)
		if ok {
			fmt.Println("自定义错误信息：", cusErr.Code, cusErr.Msg, cusErr.Time)
		}
	}
}

func sum(a, b int) (int, error) {
	if a < 0 && b < 0 {
		return 0, getCusError(1000, "两数之和，不能小于0")
	}

	return a + b, nil
}
